<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <Header :addTodo="addTodo"></Header>
      <List :todos="todos"></List>
      <Footer :qx="qx" :todos="todos"></Footer>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted,reactive,ref, toRefs, watch } from 'vue';
import Header from './components/Header.vue';
import List from './components/List.vue';
import Footer from './components/Footer.vue';
import {Todo} from './types/todo'
import Bus from './components/bus'
import {saveTodos,readTodos} from './utils/localStorageUtils'
export default defineComponent({
  components: { Header,List,Footer },
  name: 'App',
 setup(a,b){
  let state=reactive<{todos:Todo []}>({
    todos:[
      
    ]
  })
  // zj=(e:string)=>{
  //   let len=state.todos.length
  //   state.todos.push({
  //     id:len,
  //     title:e,
  //     isCompleted:false
  //   })
  // }
 let   addTodo=(e:string)=>{
   let len=state.todos.length
    state.todos.push({
      id:Math.random(),
      title:e,
      isCompleted:false
    })
  }
  onMounted(() => {
      Bus.$on("sc", (title:string) => {
       state.todos.forEach((e,index)=> {
        if(e.title==title){
          state.todos.splice(index,1)
        }
       });
      }),
      Bus.$on("xz", (title:string) => {
       state.todos.forEach((e,index)=> {
        if(e.title==title){
          state.todos[index].isCompleted=!state.todos[index].isCompleted
        }
       });
      })
      Bus.$on("qc", () => {
        state.todos=state.todos.filter(i=>!i.isCompleted)
      }),
setTimeout(()=>{
  state.todos=readTodos()
},2000)
    });
    let qx=(f:boolean)=>{
      state.todos.forEach((e,index)=> {
          state.todos[index].isCompleted=f
       });
    }
     watch(()=>state.todos,(value)=>{
   saveTodos(value)
     },{
      deep:true
     })
  return {
    ...toRefs(state),
    addTodo,
    qx,
  
  }
 }
});
</script>

<style scoped>
.todo-container{
  width: 600px;
  margin: 0 auto;
}
.todo-wrap{
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
